<?php

namespace App\Http\Controllers\Admin\Shop;

use App\Http\Controllers\Controller;
use App\Models\Shop\Account;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class AccountController extends Controller
{
   /**
    * Display a listing of the resource.
    *
    * @return \Illuminate\Http\Response
    */
   public function index(Request $request)
   {
      $where = function ($query) use ($request) {
         //按昵称手机号搜索
         if ($request->has('keyword') and $request->keyword != '') {
            $cate = $request->cate;
            $search = "%" . $request->keyword . "%";
            $query->where('b.' . $cate, 'like', $search);
         }
      };

      $accouts = DB::table('accounts as a')
         ->leftJoin('users as b', 'a.user_id', '=', 'b.id')
         ->select('a.*', 'b.name', 'b.phone')
         ->where($where)
         ->paginate(config('admin.page_size'));
      return response()->json($accouts);
   }

   /**
    * Display the specified resource.
    *
    * @param int $id 查看日志
    * @return \Illuminate\Http\Response
    */
   public function show($id)
   {
      $account_logs = DB::table('account_logs')->where('account_id', $id)->orderByDesc('created_at')->get();
      return response()->json($account_logs);
   }

   /**
    * Display the specified resource.
    *
    * @param int $id
    * @return \Illuminate\Http\Response
    */
   public function edit($id)
   {
      $account_logs = Account::with('tickets')->find($id);
      return response()->json($account_logs);
   }

   /**
    * Update the specified resource in storage.
    *
    * @param \Illuminate\Http\Request $request
    * @param int $id
    * @return \Illuminate\Http\Response
    */
   public function update(Request $request, $id)
   {
      $account = Account::with('tickets')->find($id);
      if ($request->money > 0 || $request->integral > 0 || $request->money == '' || $request->integral == '') {
         $res = $account->update([
            'money' => $account['money'] + $request->money,
            'integral' => $account['integral'] + $request->integral,
         ]);
         $account->tickets()->sync($request->ticket_id);
         //根据优惠券id查出名称
         $ticket = DB::table('tickets')->whereIn('id', $request->ticket_id)->pluck('title');
         $value = json_encode($ticket, JSON_UNESCAPED_UNICODE);

         if ($res) {
            DB::table('account_logs')->insert([
               'account_id' => $id,
               'name' => auth('admin')->user()->name,
               'desc' => '更新金额：' . $request->money . ', 更新积分：' . $request->integral . ', 优惠券：' . $value,
               'created_at' => date('Y-m-d H:i:s')
            ]);

            $info = ['status' => 1, 'msg' => '更新账户成功~'];
            return response()->json($info);
         }
      }
   }

   /**
    * Remove the specified resource from storage.
    *
    * @param int $id
    * @return \Illuminate\Http\Response
    */
   public function destroy($id)
   {
      //
   }
}
